const router = require('koa-router')()
const Flower = require('../models/Flower')

router.get('/day', async (ctx, next) => {
    const today = new Date();
    const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
    const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
    let dataDay = await Flower.find({
        created: {
            $gte:startOfDay,
            $lte:endOfDay
        }
    },'category designation grade img')
    let Data = []
    let DataKey = []
    dataDay.map((item,i)=>{
        let key = DataKey.indexOf(item.category)
        if(key == -1){
            DataKey.push(item.category)
            Data.push({
                category:item.category,
                data:[item]
            })
        }else {
            Data[key].data.push(item)
        }
    })
    ctx.body =Data
})

router.get('/week', async (ctx, next) => {
     let  week= weekday()
    const weekData = ()=> new Promise((r,e)=>{
        let data = []
        let is= 0
        let intervalId = setInterval(()=>{
            week.map(async (item, i) => {
                if (i < 6) {
                    await Flower.find({
                        created: {
                            $gte: new Date(item[0]), // Greater than or equal to one week ago
                            $lt: new Date(week[i + 1][0])  // Less than today
                        }
                    }, 'category designation grade img').then(res => {
                        data[i]=({
                            time: item[0],
                            week: item[1],
                            take: res
                        })
                    })
                }
                if (i == 6) {
                    await Flower.find({
                        created: {
                            $gte: new Date(item[0]), // Greater than or equal to one week ago
                        },
                    }, 'category designation grade img').then(res => {
                        data[6]=({
                            time: item[0],
                            week: item[1],
                            take: res
                        })
                    })
                }
            })
            if(data.length == 7){
                r(data.reverse())
                clearInterval(intervalId);
            }
        }, 300);
    })
    ctx.body = await weekData()
})

// 采集数据
router.post('/', async (ctx, next) => {
    let obj = ctx.request.body
    ctx.body =  await Flower.create(obj)
})

//采集品类数据
router.get('/li',async ctx => {
    let {category,designation} = ctx.query
    let gradeData = await Flower.aggregate([
        {
            $match: {
                designation: designation,
                category: category
            }
        },
        {
            $group: {
                _id: "$grade",
                MinPrice: {$min: '$price'},
                MaxPrice: {$max: '$price'},
                MaxSales: {$max: '$sales'},
                origin:{$push:'$origin'}
            }
        }
    ])
    ctx.body = gradeData
})


const FlowerAggregate = async (designation, category, grade, cb) => {
    console.log(designation, category, grade)
    // cb(await  Flower.find({'grade':grade}))
    cb(await Flower.aggregate([
        {
            $match: {
                designation: designation,
                category: category
            }
        },
        {
            $group: {
                _id: "$designation",
                MinPrice: {$min: '$price'},
                MaxPrice: {$max: '$price'},
                MaxSales: {$max: '$sales'},
                trading: {$last:'$$img'}
            }
        }
    ]))
}

// 获取过去7天时间
const weekday = ()=> {
    const currentDate = new Date();
    const pastDates = [];
    const dayOfWeek = currentDate.getDay();
    const weekdayNames = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    for (let i = -5; i <= 1; i++) {
        const day = currentDate.getDate() + i;
        const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), day);
        pastDates.push([date.toISOString().split('T')[0] , weekdayNames[day-1]]); // Format as YYYY-MM-DD
    }
    return pastDates
}

module.exports = router
